import React from 'react';
import { Modal, Row, Col, Select, Input, Button, message, Form, Popconfirm, Upload, Icon, Table} from 'antd';
const R = require('ramda');
import dateFormat from 'dateformat';
import Constants from '../utils/Constants';

const FormItem = Form.Item;
export default Form.create({wrappedComponentRef: true})(class ConfirmLetter extends React.Component {
	constructor(props) {
     super(props);
     this.state = {
        open: false
     }
	}

    handleOpen = () => {
      this.setState({ open: true });
    }

    handleResetFields = () => {
		    this.props.form.resetFields();
		    this.setState({ open: false });
	  }

    handleConfirmLetter = () => {
      const {form: {getFieldsValue}, dispatch, order, handleSearch } = this.props;
      let values = getFieldsValue();
      if(values.confirmResult === Constants.NUMBER_ONE){
        dispatch({
          type: "orderAgent/okConfirmLetter",
          payload: {
            id: order.id,
            onSuccess: () => {
              this.handleResetFields();
              handleSearch();
            }
          }
        })
      }else{

        dispatch({
          type: "orderAgent/cancelConfirmLetterOrder",
          payload: {
            id: order.id,
            gobackreason: values.gobackreason,
            onSuccess: () => {
              this.handleResetFields();
              handleSearch();
            }
          }
        })
      }
    }

    renderContent = (value, row, index) => {
        const obj = {
          children: value,
          props: {},
        };
        if (index === 0) {
          obj.props.colSpan = 0;
        }
        return obj;
      };

    columns = [
        {title: '服务项目', dataIndex: 'serviceItem', key: 'serviceItem',
              render: (value, row, index) => {
                const obj = {
                    children: value,
                    props: {},
                };
                if (index === 1) {
                    obj.props.rowSpan = 6;
                }else if(index === 7){
                    obj.props.rowSpan = this.props.orderProductDetails.length + 1;
                }else if(index === 8 + this.props.orderProductDetails.length){
                    obj.props.rowSpan = 2;
                }else if(index === 0 || index > 9 + this.props.orderProductDetails.length){
                    obj.props.rowSpan = 1;
                }else{
                    obj.props.rowSpan = 0;
                }
                return obj;
            },
        },
        {title: '商品名称', dataIndex: 'productname', key: 'productname',
        render: (text, row, index) => {
            if (index !== 0) {
              return text;
            }else{
                return {
                  children: text,
                  props: {
                    colSpan: 4,
                  },
                };
            }
        }},
        {title: 'HScode', dataIndex: 'producthscode', key: 'producthscode', render: this.renderContent},
        {title: '退税率(%)', dataIndex: 'taxrate', key: 'taxrate', render: this.renderContent},
        {title: '监管条件', dataIndex: 'supercondition', key: 'supercondition', render: this.renderContent},
    ]


	render() {
      const { order, supplygoodList, drawersList,
              buyer, countryCD, customer, destPort, kindPackage, lesseeInfo, orderProductDetails, placeClearance, settlement, tradeCountry,
             form: { getFieldDecorator, getFieldValue }
            } = this.props;

        let formItemLayout = {
            labelCol: {xs: {span: 24}, sm: {span: 8}},
            wrapperCol: {xs: {span: 24}, sm: {span: 14}}
        };

    let tempProductList = [];
    let drawerId = null;//开票工厂全称那个开票人的id，产品里面随便取一个
    R.map((row) => {
      drawerId = row.drawerid;
      let product = R.pick(['productname', 'producthscode', 'taxrate', 'supercondition'])(row);
      tempProductList = R.concat(tempProductList, [product]);
    }, orderProductDetails);
    //取开票工厂名称
    let drawerName = "";
    R.map((row)=>{if(row.id === drawerId) drawerName = row.name}, R.isNil(drawersList) ? [] : drawersList);

    let supplyGoods = ""
    R.map((row)=>{if (row.sprName === order.supplygoods) supplyGoods = row.sprValue}, R.isNil(supplygoodList) ? [] : supplygoodList);
    let provider = order.declarationstyle === "1" ? (R.isNil(customer) || R.isNil(customer.companyname) ? "" : R.isNil(lesseeInfo.lesseeNameCn) ? "" : lesseeInfo.lesseeNameCn) : customer.companyname;//报关抬头0自己 1客户(双抬头)


    let tableDataSourceAbove = [
      {serviceItem: '服务项目', productname: '货物出口信息', producthscode: '', taxrate: '', supercondition: ''},
      {serviceItem: '通关', productname: '收发货人', producthscode: customer.csttype+ "" === "1" ? (R.isNil(customer.companyname) ? "" :customer.companyname): (R.isNil(lesseeInfo.lesseeNameCn) ? "" :lesseeInfo.lesseeNameCn),
        taxrate: '生产销售单位', supercondition: customer.csttype+"" === "1" ? (R.isNil(customer.companyname) ? "" :customer.companyname) : provider},

      {serviceItem: '', productname: '出口口岸', producthscode: R.isNil(placeClearance) || R.isNil(placeClearance.placeName) ? "" : placeClearance.placeName, taxrate: '出口目的国', supercondition: R.isNil(countryCD) || R.isNil(countryCD.sprValue) ? "" : countryCD.sprValue},
      {serviceItem: '', productname: '贸易国(地区)', producthscode: R.isNil(tradeCountry) || R.isNil(tradeCountry.sprValue) ? "" : tradeCountry.sprValue, taxrate: '指运港', supercondition:R.isNil(destPort) ? "" : destPort },
      {serviceItem: '', productname: '报关总价', producthscode: R.isNil(order.totleamount) ? 0 : order.totleamount, taxrate: '境内货源地', supercondition: supplyGoods},
      {serviceItem: '', productname: '总毛重', producthscode: (R.isNil(order.totalgross) ? 0 : order.totalgross) + "  kg", taxrate: '总净重', supercondition: (R.isNil(order.totalweight) ? 0 : order.totalweight) + "  kg"},
      {serviceItem: '', productname: '总件数', producthscode: R.isNil(order.totalpacknum) ? 0 : order.totalpacknum, taxrate: '包装种类', supercondition: R.isNil(kindPackage) || R.isNil(kindPackage) ? "" : kindPackage},
      {serviceItem: '产品', productname: '商品名称', producthscode: "HScode", taxrate: '退税率(%)', supercondition: '监管条件'},
    ];
    let tableDataSourceBelow = [
      {serviceItem: '外汇', productname: '付汇人', producthscode: R.isNil(buyer) || R.isNil(buyer.name) ? "" : buyer.name, taxrate: '付款方式', supercondition: R.isNil(settlement) || R.isNil(settlement.sprValue) ? "" : settlement.sprValue},
      {serviceItem: '', productname: '付汇金额(币种)', producthscode: '', taxrate: '付汇时间', supercondition: '货物报关放行之日起90日内'},
      {serviceItem: '退税', productname: '开票工厂全称', producthscode: drawerName, taxrate: '开票时间', supercondition: '货物报关放行之日起90日内'},
      {serviceItem: '退税预垫', productname: '预垫退税金额', producthscode: '', taxrate: '币种', supercondition: R.isNil(order.currencytype) ? "" : order.currencytype},
    ]
    tableDataSourceAbove = R.concat(R.concat(tableDataSourceAbove, tempProductList), tableDataSourceBelow);

    let key = 1;
    let tableDataSourceAboveWithKey = tableDataSourceAbove.map((product)=> {
      product.key = key++;
      return product;
    });

		return (
            <Modal wrapClassName="vertical-center-modal" maskClosable={false} visible={this.state.open} title="确认函详情" width={950} footer={null} onCancel={this.handleResetFields.bind(this)}>
                <div style={{textAlign: 'center', marginTop: 30}}>
                    <span><b><font size="4">出口服务订单确认函</font></b></span>
                    <span style={{textAlign: 'left', lineHeight: 2}}><p>至{R.isNil(lesseeInfo.lesseeNameCn) ? "" : lesseeInfo.lesseeNameCn}:</p></span>
                    <span style={{textAlign: 'left', lineHeight: 2}}><p>我方对以下委托贵司出口的服务项目及相关项目明细信息了解并认可:同意本确认函出具后,需待贵司确认接受委托后双方的委托服务关系方成立.</p></span>
                    <span style={{textAlign: 'left', lineHeight: 2}}><p>我方就委托贵司办理的产品出口服务及货物相关信息确认如下:</p></span>
                    <span style={{textAlign: 'left', lineHeight: 2}}><p>一:服务项目及货物出口信息:</p></span>
                </div>
                <Table showHeader={false} pagination={false} bordered={true} columns={this.columns} size={'small'} style={{marginTop: 0}} dataSource={tableDataSourceAboveWithKey} width="80%"/>
                <div style={{marginTop: 10}}>
                    <span style={{lineHeight: 2}}><p>我方确认上述出口货物及信息准确真实、合法有效,如因上述信息错误导致的一切费用、损失及责任均由我方承担.我方承诺上述货物已与海外买家</p></span>
                    <span style={{lineHeight: 2}}><p>签订相关的贸易合同并与海外买家约定由贵司代为出口及代为收汇.</p></span>
                </div>
                <div style={{marginTop: 10}}>
                    <span style={{lineHeight: 2}}><p>委托单位: {R.isNil(customer) || R.isNil(customer.companyname) ? "" : customer.companyname}</p></span>
                    <span style={{lineHeight: 3}}><p>时间: {dateFormat(new Date(), 'yyyy年mm月dd日')}</p></span>
                </div>

              <div className="ant-menu-item-divider" style={{marginTop: 19}}/>
              <div style={{display: 'flex', marginTop: 18, marginLeft: 40}}>
                <Col span={8}>
                  <FormItem {...formItemLayout} label={<span>审批结果</span>}>
                    {getFieldDecorator('confirmResult', {
                      rules: [{
                        required: true, message: '请选择审批结果'
                      }],
                      initialValue: "1"
                    })(
                      <Select style={{width: '100%'}}>
                        <Select.Option value="1" key="1">确认收函</Select.Option>
                        <Select.Option value="2" key="2">拒绝收函</Select.Option>
                      </Select>
                    )}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem {...formItemLayout} label={<span>退回原因</span>}>
                    {getFieldDecorator('gobackreason', {
                      rules: [{
                        required: getFieldValue("confirmResult") === '2', message: '请输入退回原因'
                      }],
                    })(
                      <Input.TextArea maxLength="100" autosize={true}/>
                    )}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <Button style={{marginTop: 8}} type="primary" key="confirm" icon="check"
                          onClick={this.handleConfirmLetter.bind(this)}>确认收函</Button>
                </Col>
              </div>
            </Modal>
		)
	}
})
